package com_github_lib_base.ext

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.content.pm.PackageInstaller
import android.content.pm.PackageManager
import android.net.Uri
import android.util.Log
import com.shudong.lib_base.ext.appContext
import com_github_lib_base.APPSTORE_APPDETAIL_NAME
import com_github_lib_base.APPSTORE_APP_ID
import com_github_lib_base.currentActivity
import androidx.core.net.toUri

const val PACKAGE_NAME: String = "package_name"

fun String.openApp(url: String? = null, pkName: String = appContext.packageName) {
    val packageManager = appContext.packageManager

    // 如果提供了 URL，优先尝试打开 URL
    if (!url.isNullOrEmpty()) {
        try {
            val intent = Intent(Intent.ACTION_VIEW, url.toUri())
            // 可选：尝试优先使用目标应用的包名（如果包名有效）
            if (this.isNotBlank()) {
                intent.setPackage(this)
            }
            currentActivity?.startActivity(intent)
            return
        } catch (e: ActivityNotFoundException) {
            // 如果 URL 无法打开，尝试回退到浏览器
            launchByPackageName(this, packageManager)
            return
        }
    }

    // 按包名/类名或包名启动应用的逻辑
    val parts = this.split("/")
    if (parts.size == 2) {
        // 包名和类名格式：packageName/activityClassName
        val packageName = parts[0]
        val activityClassName = if (parts[1].startsWith(".")) {
            // 如果 activityName 以 "." 开头，自动补全完整路径
            packageName + parts[1]
        } else {
            parts[1]
        }
        try {
            val intent = Intent().setClassName(packageName, activityClassName).apply {
                data = Uri.fromParts("package", pkName, null)
            }
            currentActivity?.startActivity(intent)
        } catch (e: ActivityNotFoundException) {
            // 如果类名无效，回退到包名启动逻辑
            launchByPackageName(packageName, packageManager)
        }
    } else {
        // 仅包名格式
        launchByPackageName(this, packageManager)
    }
}

/**
 * 尝试通过包名启动应用，或回退到 App Store/Google Play
 */
private fun launchByPackageName(packageName: String, packageManager: PackageManager) {
    // 尝试启动应用
    var intent = packageManager.getLaunchIntentForPackage(packageName)
    if (intent == null) intent = packageManager.getLeanbackLaunchIntentForPackage(packageName)
    if (intent != null) {
        currentActivity?.startActivity(intent)
        return
    }

    // 尝试打开自定义 App Store
    // 尝试优先使用自定义 Action 跳转
    val actionIntent = Intent("com.smart.android.appstoretv.ACTION_SHOW_DETAILS").apply {
        putExtra(PACKAGE_NAME, arrayOf(packageName))
        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
    }

    try {
        currentActivity?.startActivity(actionIntent)
    } catch (e: ActivityNotFoundException) {
        // 自定义 Action 不可用，尝试包名+类名方式
        try {
            val explicitIntent =
                Intent(Intent.ACTION_MAIN).setClassName(APPSTORE_APP_ID, APPSTORE_APPDETAIL_NAME)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
                    .putExtra(PACKAGE_NAME, arrayOf(packageName))
            currentActivity?.startActivity(explicitIntent)
        } catch (e2: ActivityNotFoundException) {
            // 自定义 App Store 不可用，尝试 Google Play
            try {
                currentActivity?.startActivity(
                    Intent(Intent.ACTION_VIEW, "market://details?id=$packageName".toUri())
                        .setPackage("com.android.vending")
                )
            } catch (e3: ActivityNotFoundException) {
                // 最后回退到 Google Play 网页版
                currentActivity?.startActivity(
                    Intent(
                        Intent.ACTION_VIEW,
                        "https://play.google.com/store/apps/details?id=$packageName".toUri()
                    )
                )
            }
        }
    }

}

fun Context.isAppUninstallable(packageName: String): Boolean {
    return try {
        val packageManager = packageManager
        val applicationInfo = packageManager.getApplicationInfo(packageName, 0)

        // 检查应用是否是系统应用或被标记为不可卸载
        val isSystemApp = applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM != 0
        val isUpdatedSystemApp =
            applicationInfo.flags and ApplicationInfo.FLAG_UPDATED_SYSTEM_APP != 0

        // 如果应用不是系统应用并且不是更新的系统应用，则可以卸载
        !isSystemApp && !isUpdatedSystemApp
    } catch (e: PackageManager.NameNotFoundException) {
        // 如果包名未找到，则认为不可卸载
        false
    }
}

@SuppressLint("MissingPermission")
fun Context.uninstallPackage(packageName: String): Boolean {
    var success = false
    try {
        val packageManager = packageManager
        val packageInstaller = packageManager.packageInstaller
        val params =
            PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL).apply {
                setAppPackageName(packageName)
            }
        val sessionId = packageInstaller.createSession(params)
        val intent = Intent(Intent.ACTION_DELETE).apply {
            data = "package:$packageName".toUri()
        }
        val pendingIntent = PendingIntent.getBroadcast(
            this, sessionId, intent, PendingIntent.FLAG_IMMUTABLE
        )
        val sender = pendingIntent.intentSender
        packageInstaller.uninstall(packageName, sender)
        success = true
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return success
}


private val appNameCache = mutableMapOf<String, String>()

fun String.getAppNameWithCache(): String? {
    val appname = appNameCache[this] ?: try {
        appContext.packageManager.getApplicationInfo(this, 0)
            .loadLabel(appContext.packageManager)
            .toString()
            .also { appNameCache[this] = it }
    } catch (e: PackageManager.NameNotFoundException) {
        null
    }
    return appname
}

// 获取应用版本名称（Version Name）的扩展函数
val Context.appVersionName: String
    get() {
        return try {
            val packageInfo: PackageInfo = packageManager.getPackageInfo(packageName, 0)
            packageInfo.versionName ?: "Unknown"
        } catch (e: PackageManager.NameNotFoundException) {
            "Unknown"
        }
    }

// 获取应用版本号（Version Code）的扩展函数
val Context.appVersionCode: Long
    get() {
        return try {
            val packageInfo: PackageInfo = packageManager.getPackageInfo(packageName, 0)
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
                packageInfo.longVersionCode
            } else {
                @Suppress("DEPRECATION")
                packageInfo.versionCode.toLong()
            }
        } catch (e: PackageManager.NameNotFoundException) {
            -1
        }
    }